#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(char *args)
{
    std::cout << args << " server_ip server_port" << std::endl;
}
#define NUM 1024

int main(int argc, char *args[])
{
    if (argc != 3)
    {
        Usage(args[0]);
        return 1;
    }
    // 1. 创建套接字，打开网络文件
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket failed :" << errno << std::endl;
        return 2;
    }

    // 2.bind
    // 但是客户端不需要绑定端口号，系统会自动分配，同时要明确服务器的端口和ip
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(args[2]));
    server.sin_addr.s_addr = inet_addr(args[1]);

    // 3. 发送请求

    while (true)
    {
        // std::string s;
        // std::cout << "请输入# ";
        // std::cin >> s;
        std::cout << "MyShell# ";

        char line[NUM];
        fgets(line, sizeof(line), stdin);

        // sendto(sock, s.c_str(), s.size(), 0, (struct sockaddr *)&server, sizeof(server));
        sendto(sock, line, strlen(line), 0, (struct sockaddr *)&server, sizeof(server));

        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buf[NUM];

        ssize_t sz = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&tmp, &len);

        if (sz > 0)
        {
            buf[sz] = 0;

            std::cout << buf << std::endl;
        }
    }

    return 0;
}